package mn.idax.exchange.otc.service;

import mn.idax.exchange.otc.dto.ConnectionDTO;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jack_huang
 * @Date: 2019/7/5 16:57
 */
@Service
public class MemoryService implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemoryService.class);

    @Override
    public void run(String... strings){

        ScheduledExecutorService connectionsService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("clearMemoryConnections").daemon(true).build());

        connectionsService.scheduleAtFixedRate(() -> {

            //移除长时间未传token的连接
            Collection<ConnectionDTO> connections = ChatRoomService.CONNECTIONS.values();
            if (!CollectionUtils.isEmpty(connections)) {
                long current = System.currentTimeMillis();

                for (ConnectionDTO value : connections) {
                    if (value.getTimestamp() != 0 && current - value.getTimestamp() > 5) {
                        try {
                            value.getResource().close();
                        } catch (IOException e) {
                            LOGGER.info("connectionsService fail,{}", ExceptionUtils.getStackTrace(e));
                        }
                    }

                }
            }

        }, 0, 5, TimeUnit.SECONDS);


    }
}
